package system

import (
	"context"
	"slices"
	"strconv"

	"portal/internal/errorx"
	"portal/internal/svc"
	"portal/internal/tool/auth"
	"portal/internal/types"
	"portal/model"

	"github.com/zeromicro/go-zero/core/logx"
)

type DeleteUserLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
	menuModel model.SysMenuModel
	userModel model.SysUserModel
	deptModel model.SysDeptModel
}

func NewDeleteUserLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DeleteUserLogic {
	return &DeleteUserLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
		menuModel: model.NewSysMenuModel(svcCtx.Orm),
		userModel: model.NewSysUserModel(svcCtx.Orm),
		deptModel: model.NewSysDeptModel(svcCtx.Orm),
	}
}

func (l *DeleteUserLogic) DeleteUser(req *types.IdRequest) (resp *types.CommonResponse, err error) {
	// todo: add your logic here and delete this line
	// 软删除
	err = auth.HasPermission(l.menuModel,l.ctx,"system:user:remove")
	if err != nil {
		return nil,errorx.Unauthorized
	}

	roles,err := auth.GetRoles(l.ctx)
	if err != nil {
		return nil,errorx.AuthNoFound
	}
	strDeptId, err := auth.GetDeptId(l.ctx)
	if err != nil {
		return nil, err
	}
	deptId, _ := strconv.Atoi(strDeptId)

	// 判断是否是admin或者该成员是否是他管理的部门下的用户
	if isAdmin,_ := auth.IsAdmin(l.ctx) ; !isAdmin {
		var deptvos []*types.Dept
		deptvos,err = getDepts(l.ctx,int64(deptId),roles,l.deptModel,&types.ListDeptRequest{})
		if err != nil {
			return nil,errorx.AuthNoFound
		}
		user,err := l.userModel.FindOne(l.ctx,req.Id)
		if err != nil {
			return nil,errorx.SqlSearchError
		}
		inHere := slices.ContainsFunc(deptvos,func(n *types.Dept)bool{
			return n.DeptId == user.DeptId.Int64
		})
		if !inHere {
			return nil,errorx.NewBizError(500,"无删除此用户权限")
		}
	}

	err = l.userModel.DelUser(l.ctx,nil,req.Id)

	return &types.CommonResponse{
		Status: 200,
		Msg: "删除成功",
	},err
}
